﻿using MediatR;
using PublicClass;
using S.Produce.Domains;
using S.Produce.Infrastructure;
using S.Produce.Read.Api.Application.Commands.DeliveryCommands;

namespace S.Produce.Read.Api.Application.CommandHandlers.DeliveryCommandHandlers
{
    /// <summary>
    /// 查询，显示，分页种母分娩记录
    /// </summary>
    public class DeliverySelectCommandHandler : IRequestHandler<DeliverySelectCommand, PageInfo<Delivery>>
    {
        private readonly IRepository<Delivery> _repository;

        /// <summary>
        /// 构造方式注入
        /// </summary>
        /// <param name="repository"></param>
        public DeliverySelectCommandHandler(IRepository<Delivery> repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 查询，显示，分页种母分娩记录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PageInfo<Delivery>> Handle(DeliverySelectCommand request, CancellationToken cancellationToken)
        {
            var deliveryList = await _repository.GetAllAsync();
            var info = deliveryList.AsQueryable().Where(x => !x.IsDel);
            if (!string.IsNullOrEmpty(request.InDate))
            {
                var sdate = request.InDate.Split(",")[0];
                var edate = request.InDate.Split(",")[1];
                info = info.Where(x => x.DeliveryDate >= DateTime.Parse(sdate) && x.DeliveryDate <= DateTime.Parse(edate));
            }
            if (!string.IsNullOrEmpty(request.Earbugles))
            {
                info = info.Where(x => x.Earbugles == request.Earbugles);
            }
            if (!string.IsNullOrEmpty(request.OutBuildings))
            {
                info = info.Where(x => x.CurrentBuilding == request.OutBuildings);
            }
            if (!string.IsNullOrEmpty(request.InBuildings))
            {
                info = info.Where(x => x.OriginallyDorm == request.InBuildings);
            }
            if (!string.IsNullOrEmpty(request.nestNumber))
            {
                info = info.Where(x => x.NestNumber == request.nestNumber);
            }
            if (!string.IsNullOrEmpty(request.head))
            {
                info = info.Where(x => x.Head == request.head);
            }
            int totalCount = info.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            info = info.OrderByDescending(x => x.CreateDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);
            return new PageInfo<Delivery>
            {
                totalCount = totalCount,
                pageCount = pageCount,
                datas = info.ToList()
            };
        }
    }
}
